package vip.pwztx.api.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vip.pwztx.api.result.Result;

/**
 * 全局异常拦截
 *
 * @author zhoubaohua
 * @date 2020/9/11
 */
@RestControllerAdvice(basePackages = "vip.pwztx.controller")
public class GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 处理自定义的业务异常
     *
     * @param pwzException 自定义异常
     * @return 异常结果
     */
    @ExceptionHandler(value = PwzException.class)
    public Result pwzExceptionHandler(PwzException pwzException) {
        pwzException.printStackTrace();
        logger.error("发生业务异常！原因是：{}", pwzException.getMessage());
        return Result.throwable(pwzException);
    }

    /**
     * 处理空指针的异常
     *
     * @param nullPointerException 空指针异常
     * @return 异常结果
     */
    @ExceptionHandler(value = NullPointerException.class)
    public Result nullExceptionHandler(NullPointerException nullPointerException) {
        nullPointerException.printStackTrace();
        logger.error("发生空指针异常！原因是: {}", nullPointerException.getMessage());
        return Result.throwable(nullPointerException);
    }

    /**
     * 处理其他异常
     *
     * @param exception 其他异常
     * @return 异常结果
     */
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception exception) {
        exception.printStackTrace();
        logger.error("未知异常！原因是: {}", exception.getMessage());
        return Result.throwable(exception);
    }

}
